package com.kxn.multi.module.api.controller;

import com.kxn.multi.module.common.pojo.ApiResult;
import com.kxn.multi.module.service.dto.api.mq.CommonMessageParam;
import com.kxn.multi.module.service.dto.api.mq.MQContentParam;
import com.kxn.multi.module.service.dto.api.mq.TransactionMessageParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.kxn.multi.module.common.constant.MqConstant;

import javax.annotation.Resource;

@Slf4j
@Api(tags = {"mq测试接口"})
@RestController
@RequestMapping("/api/mq")
public class MqController {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @ApiOperation(value = "通用消息")
    @PostMapping("/common/message")
    public ApiResult commonMessage(@Validated @RequestBody CommonMessageParam param) {
        Message<CommonMessageParam> messagePayload = MessageBuilder.withPayload(param).build();
        rocketMQTemplate.send(MqConstant.COMMON_TOPIC, messagePayload);
        return ApiResult.success();
    }

    @PostMapping("/enqueue")
    public ApiResult enqueue(@Validated @RequestBody MQContentParam param) {
        Message<MQContentParam> messagePayload = MessageBuilder.withPayload(param).build();
        rocketMQTemplate.send(MqConstant.TEST_TOPIC, messagePayload);
        return ApiResult.success();
    }

    @ApiOperation(value = "顺序消息")
    @PostMapping("/order/message")
    public ApiResult orderMessage(@Validated @RequestBody MQContentParam param) {
        Message<MQContentParam> messagePayload = MessageBuilder.withPayload(param).build();
        //顺序消息，参数hashKey可以指定消息到具体的队列中，也就是同一个hashkey会保存在同个mq中
        SendResult result = rocketMQTemplate.syncSendOrderly(MqConstant.ORDER_TOPIC, messagePayload,param.getQueueHashKey());
        return ApiResult.success(result);
    }

    @ApiOperation(value = "事务消息")
    @PostMapping("/transaction/message")
    public ApiResult transactionMessage(@Validated @RequestBody TransactionMessageParam param) {
        log.info("获取请求消息-transactionMessage：{}", param);
        Message<TransactionMessageParam> messagePayload = MessageBuilder.withPayload(param).build();
        //顺序消息，参数hashKey可以指定消息到具体的队列中，也就是同一个hashkey会保存在同个mq中
        SendResult result = rocketMQTemplate.sendMessageInTransaction(MqConstant.TRANSACTION_TOPIC, messagePayload, null);
        return ApiResult.success(result);
    }





}
